//
//  XLComposeViewController.swift
//  SinaWeibo
//
//  Created by 李凯 on 16/9/10.
//  Copyright © 2016年 kevin. All rights reserved.
//

import UIKit

class XLComposeViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()

        setupUI()
        
        //注册通知
        NotificationCenter.default.addObserver(self, selector: #selector(
            keyboardWillChangeFrame(noti:)), name: NSNotification.Name.UIKeyboardWillChangeFrame, object: nil)
    }

    func setupUI() {
        
        self.view.backgroundColor = UIColor.white
        //设置左边返回按钮
        self.navigationItem.leftBarButtonItem = UIBarButtonItem(title: "返回", target: self, action: #selector(back))
        //设置导航栏的标题
        self.navigationItem.titleView = titleLabel
        //设置右侧按钮
        self.navigationItem.rightBarButtonItem = UIBarButtonItem(customView: rightButton)
        //默认右侧按钮不可用
        self.navigationItem.rightBarButtonItem!.isEnabled = false
        
        view.addSubview(textView)
        view.addSubview(composeToolBar)
        view.addSubview(composePicView)
        
        //布局
        textView.snp_makeConstraints { (make) in
            make.edges.equalTo(view)
        }
        composeToolBar.snp_makeConstraints { (make) in
            make.bottom.left.right.equalTo(self.view)
            make.height.equalTo(44)
        }
        composePicView.snp_makeConstraints { (make) in
            make.top.equalTo(textView).offset(100)
            make.left.equalTo(textView).offset(10)
            make.width.equalTo(textView.snp_width).offset(-20)
            make.height.equalTo(composePicView.snp_width)
        }
    }
    
    func back() {
        self.dismiss(animated: true, completion: nil)
    }
    
    //系统已发送通知, 就执行该方法
    func keyboardWillChangeFrame(noti: Notification) {
        //取到键盘最终停留的位置
        let frame = (noti.userInfo![UIKeyboardFrameEndUserInfoKey] as! NSValue).cgRectValue
        //取到键盘的执行动画时间
        let duration = (noti.userInfo![UIKeyboardAnimationDurationUserInfoKey] as! NSNumber).doubleValue
        //更新toolbar的位置
        composeToolBar.snp_updateConstraints { (make) in
             make.bottom.equalTo(self.view).offset(frame.origin.y - HMScreenH)
        }
        UIView.animate(withDuration: duration) { 
            self.view.layoutIfNeeded()
        }
    }
    //移除通知
    deinit {
        NotificationCenter.default.removeObserver(self)
    }
    
    //懒加载
    //输入框
    lazy var textView: XLTextView = {
        let textView = XLTextView()
        textView.placeHolder = "站为文字"
        textView.delegate = self
        textView.font = UIFont.systemFont(ofSize: 16)
        textView.alwaysBounceVertical = true
        return textView
    }()
    
    internal lazy var rightButton: UIButton = {
        let button = UIButton()
        button.titleLabel?.font = UIFont.systemFont(ofSize: 14)
        // 设置不同状态的按钮背景图
        button.setBackgroundImage(UIImage(named: "common_button_orange"), for: UIControlState.normal)
        button.setBackgroundImage(UIImage(named: "common_button_orange_highlighted"), for: UIControlState.highlighted)
        button.setBackgroundImage(UIImage(named: "common_button_white_disable"), for: UIControlState.disabled)
        // 设置不同状态下的按钮文字颜色
        button.setTitleColor(UIColor.gray, for: UIControlState.disabled)
        button.setTitleColor(UIColor.white, for: UIControlState.normal)
        button.setTitle("发送", for: UIControlState.normal)
        // 设置按钮的大小
        button.frame.size = CGSize(width: 44, height: 30)
        
        return button
        
    }()

    
    lazy var titleLabel: UILabel = {
        let label = UILabel()
        //两行
        label.numberOfLines = 0
        //居中
        label.textAlignment = .center
        //字体大小
        label.font = UIFont.systemFont(ofSize: 16)
        //文字
        if let name = XLUserAccountViewModel.sharedModel.account?.name {
            let title = "发微博\n\(name)"
            //1. 初始化一个可变的富文本
            let attributedText = NSMutableAttributedString(string: title)
            //2. 取到范围
            let range = (title as NSString).range(of: name)
            //3. 给富文本添加属性
            attributedText.addAttributes([NSFontAttributeName: UIFont.systemFont(ofSize: 14), NSForegroundColorAttributeName: UIColor.lightGray], range: range)
            //4. 赋值
            label.attributedText = attributedText
        }else{
            label.text = "发微博"
        }
        //设置大小
        label.sizeToFit()
        return label
    }()
    
    lazy var composeToolBar: XLComposeToolBar = {
        let composeToolBar = XLComposeToolBar()
        //设置代理
        composeToolBar.delegate = self
        return composeToolBar
    }()
    
    lazy var composePicView: XLComposePicView = {
        let picView = XLComposePicView(frame: CGRect.zero, collectionViewLayout: UICollectionViewFlowLayout())
        picView.backgroundColor = UIColor.white
        picView.addImgBtnClickClosure = {
            print("点击➕按钮了");
            //弹出选择图片的控制器
            self.selectPic()
        }
        return picView
    }()
}

extension XLComposeViewController: UITextViewDelegate {
    func textViewDidChange(_ textView: UITextView) {
        navigationItem.rightBarButtonItem?.isEnabled = textView.hasText
    }
    
    func scrollViewDidScroll(_ scrollView: UIScrollView) {
        // 取消第一响应者
        self.textView.resignFirstResponder()
        //self.view.endEditing(true)
    }
}

extension XLComposeViewController: XLComposeToolBarDelegate {
    //实现代理方法
    func composeToolBar(toolBar: XLComposeToolBar, type: composeToolBarBtnType) {
        switch type {
        case .picture:
            selectPic()
        case .mention:
            print("点击了@按钮")
        case .emoticon:
            print("点击了表情按钮")
        case .trend:
            print("点击了#按钮")
        case .add:
            print("点击了+按钮")
        }
    }
    
    //弹图片控制器的方法
    func selectPic() {
        let vc = UIImagePickerController()
        vc.sourceType = .photoLibrary
        vc.delegate = self
        self.present(vc, animated: true, completion: nil)
    }
    
}

extension XLComposeViewController: UIImagePickerControllerDelegate, UINavigationControllerDelegate {
    //实现代理方法
    func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
        //print("info")
        let image = info["UIImagePickerControllerOriginalImage"] as! UIImage
        //将图片写入桌面: 需要先将图片转成NSData
        //let data = UIImagePNGRepresentation(image)!
        //(data as NSData).write(toFile: "/Users/likai/Desktop/aaa.png", atomically: true)
        
        //先对图片进行压缩, 再添加
        let img = image.scaleTo(width: 600)
        composePicView.addImage(image: img)
        //关闭控制器
        picker.dismiss(animated: true, completion: nil)
    }
}





